package main

import (
	"encoding/json"
	"fmt"
	"github.com/gen2brain/go-fitz"
	"image/png"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

const pdfDir = "/Users/zhangchao/Documents/pdfs/"
const imageDir = "/Users/zhangchao/Documents/pdf-images/"

type file struct {
	Name     string `json:"name"`
	PdfUrl   string `json:"pdf_url"`
	ImageUrl string `json:"image_url"`
}

type JsonResult  struct{
	Code int `json:"code"`
	Msg  string `json:"msg"`
	Data []file `json:"data"`
}

// 生成图片
func genImage(fileName string) {
	_fileName := filepath.Join(pdfDir + fileName)
	doc, err := fitz.New(_fileName)

	if doc.NumPage() > 1 {
		img, err := doc.Image(0)
		if err != nil {
			panic(err)
		}

		var exportImage strings.Builder
		exportImage.WriteString(imageDir)
		exportImage.WriteString(strings.Replace(fileName, ".pdf", ".png", 1))
		f, err := os.Create(filepath.Join("", exportImage.String()))
		if err != nil {
			panic(err)
		}
		err = png.Encode(f, img)
		if err != nil {
			panic(err)
		}

		f.Close()
	}
	if err != nil {
		panic(err)
	}
	defer doc.Close()

}

// 检测 pdf 是否有图片
func checkItHasImage(file string) bool {
	_, err := os.Stat(filepath.Join(imageDir, strings.Replace(file, ".pdf", ".png", 1)))
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

// 获取 pdf 列表
func GetPdfs(w http.ResponseWriter, req *http.Request) {
	var pdfs []file
	files, _ := os.ReadDir(pdfDir)
	for _, f := range files {
		var _file file
		if !checkItHasImage(f.Name()) {
			genImage(f.Name())
		}
		_file.ImageUrl = strings.Replace(f.Name(), ".pdf", ".png", 1)
		_file.PdfUrl = f.Name()
		_file.Name = strings.Replace(f.Name(), ".pdf", "", -1)
		pdfs = append(pdfs, _file)
	}


	w.Header().Set("content-type","text/json")

	data, err := json.Marshal(JsonResult{
		Code: 200,
		Msg:  "查询成功",
		Data: pdfs,
	})
	if err != nil {
		fmt.Printf("json.marshal failed, err:", err)
		w.WriteHeader(400)
		w.Write([]byte(fmt.Sprintf("json.marshal failed, err:", err)))
		return
	}
	w.Write(data)

}

func main() {
	http.HandleFunc("/api/pdfs", GetPdfs)


	fmt.Println("|-----------------------------------|")
	fmt.Println("|             go-server             |")
	fmt.Println("|-----------------------------------|")
	fmt.Println("|  Go Http Server Start Successful  |")
	fmt.Println("|    Port:" + "8081" + "     Pid:" + fmt.Sprintf("%d", os.Getpid()) + "        |")
	fmt.Println("|-----------------------------------|")
	fmt.Println("")

	http.ListenAndServe(":8081", nil)
}
